#!/bin/bash

export LANG=en_US.UTF-8

#dingding
token_url='https://oapi.dingtalk.com/robot/send?access_token=XXXXXXXXXX'

location='AWS'

graylog_server='127.0.0.1'
user='admin'
passwd='passwd'
url="http://${graylog_server}:9000/api/search/universal/absolute/export?query=streams%3A"
streams='619517cdcf90be6a7b8b8b8f'
from=`date -d '-2min' +"%F %T" |sed -r 's/ /%20/g;s/:/%3A/g'`
to=`date -d '-1min' +"%F %T" |sed -r 's/ /%20/g;s/:/%3A/g'`
fields='app_id,message'
sort_str="sort=timestamp&decorate=true"

file_name=`date -d now +"%F_%T.csv"|sed 's/:/-/g'`
tmp="/tmp/${file_name}"

trap "exit 1"           HUP INT PIPE QUIT TERM
trap "test -f ${tmp} && rm -f ${tmp}"  EXIT

#cmd="mutt -s ${subj} -e 'set realname=graylog_alert'"

curl -u ${user}:${passwd} -s "${url}${streams}&from=${from}&to=${to}&fields=${fields}&${sort_str}" > ${tmp} ||\
eval "echo 请求graylog失败!;exit 1"

#test -s ${tmp} && head10=`head -n10 ${tmp}` && num=`wc -l ${tmp}|awk '{print $1}'`
#cat ${tmp}|sort -u

regx='Err|rror|erro|ERR|Invalid|illegal'
ignore_re='error reading communication packets'
num=`cat $tmp|grep -E "$regx"|grep -Ev "${ignore_re}"|wc -l`
# ${tmp}

if [ ${num} -gt 0 ]; then
info=`cat ${tmp}|grep -E "${regx}"|grep -Ev '${ignore_re}'|sed 's/"//g'|head -n 20`
mydate=`date -d now +"%F %T"`
msg="中间件日志告警
date: ${mydate}

$info"

curl "${token_url}" \
   -H 'Content-Type: application/json' \
   -d "{'msgtype': 'text',
        'text': {
             'content': \"${msg}\"
        },
      'at': {
            'isAtAll': false
        }
      }"
fi
